package com.qdu.controller;


import com.alibaba.fastjson.JSONObject;
import com.qdu.bean.Power;
import com.qdu.bean.User;
import com.qdu.commons.AccessToken;
import com.qdu.util.EncryptUtil;
import com.qdu.commons.Result;
import com.qdu.service.UserService;
import com.qdu.util.JWTUtil;
import com.qdu.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("/selectposition")
    public Result<List<Power>> selectPosition(){
        List<Power> powerList = userService.selectPosition();
        return Result.success(powerList);
    }

    @RequestMapping("/checkname")
    public Result<String> checknmae(String name){
        User user = userService.getUser(name);
        if(ObjectUtils.isEmpty(user)){
            return Result.success("用户名可以使用");
        }else {
            return Result.failed("用户名重复");
        }
    }

    @RequestMapping("/register")
    public Result<String> register(@RequestBody User user){
        boolean isRegister = userService.register(user);
        if(isRegister){
            return Result.success("注册成功");
        }else {
            return Result.failed("服务器出现异常，请刷新再次尝试");
        }
    }


    @GetMapping("/{name}")
    /*查这个*/
    public User getUser(@PathVariable String name) {

        log.info("name -{}", name);
        return userService.getUser(name);
    }

    @PostMapping("/login")
    public Result<String> login(@RequestParam String name,
                                @RequestParam String password){
        log.info("name -{}",name);
        password = DigestUtils.md5Hex(password);
        User user = userService.getUser(name,password);

        Assert.notNull(user,"用户名或密码错误");
        long currentTimeMillis = System.currentTimeMillis();
        String token= JWTUtil.createToken(user.getName(),currentTimeMillis);
        redisUtil.set(name,currentTimeMillis,60*30);
        return Result.success(token);


/*        password = DigestUtils.md5Hex(password);
        if (!StringUtils.equals(password,user.getPassword())){
            log.warn("密码错误");
            return Result.failed("用户名或密码错误");
        }

        *//*创建Access Token*//*
        AccessToken assessToken = new AccessToken(name);
        //序列化为json字符串，然后加密
        String jsonString = JSONObject.toJSONString(assessToken);
        String token = EncryptUtil.encrypt(jsonString);
        return Result.success(token);*/
    }

}
